<script setup> 
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addCommentApi, queryInfoApi, updateCommentApi, deleteCommentApi } from '@/api/comment'

//评论列表数据
const commentList = ref([])

const searchComment = ref({
  content: '',
  userId: '',
  strategyId: '',
  parentId: ''
})

onMounted(async () => {
  handleSearch()
})

//查询评论
const handleSearch = async () => {
  console.log('Search:', searchComment.value)
  const result = await queryPageApi(searchComment.value.content, searchComment.value.userId, searchComment.value.strategyId, searchComment.value.parentId, currentPage.value, pageSize.value);
  if(result.code){
    commentList.value = result.data.records
    total.value = result.data.total
  }
}

const handleReset = () => {
  // 清空表单
  searchComment.value = {
    content: '',
    userId: '',
    strategyId: '',
    parentId: ''
  }
  handleSearch()
}

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 操作处理
const handleEdit = async (id) => {
  console.log('Edit:', id)
  try {
    const result = await queryInfoApi(id);
    if(result.code){
      dialogVisible.value = true
      dialogTitle.value = '修改评论'
      // 确保包含id字段
      comment.value = {
        ...result.data,
        id: id // 明确确保id字段存在
      }
      // 确保表单引用已存在再调用resetFields
      if (commentFormRef.value) {
        commentFormRef.value.resetFields()
      }
    } else {
      ElMessage.error('获取评论信息失败')
    }
  } catch (error) {
    console.error('编辑操作出错:', error)
    ElMessage.error('编辑过程中发生错误')
  }
}

// 删除单个评论
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该评论吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除评论
    const result = await deleteCommentApi(id);
    if(result.code){
      ElMessage.success('删除评论成功') 
      handleSearch()
    }else{
      ElMessage.error(result.msg || '删除失败')
    }
  })
}

//新增评论
const addComment = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增评论'
  comment.value = {
    id: undefined,
    content: '',
    userId: '',
    strategyId: '',
    parentId: null
  }
  // 确保表单引用已存在再调用resetFields
  if (commentFormRef.value) {
    commentFormRef.value.resetFields()
  }
}

//新增/修改表单
const commentFormRef = ref(null)
const comment = ref({
  id: undefined,
  content: '',
  userId: '',
  strategyId: '',
  parentId: null
})

//表单校验规则
const rules = ref({
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 500, message: '评论内容长度应在1到500个字符之间', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', message: '用户ID必须是数字', trigger: 'blur' }
  ],
  strategyId: [
    { required: true, message: '请输入文章ID', trigger: 'blur' },
    { type: 'number', message: '文章ID必须是数字', trigger: 'blur' }
  ]
});

// 控制弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增评论')

//保存评论信息
const save = async () => {
  // 确保表单校验通过
  commentFormRef.value.validate(async valid => {
    if(valid){ // 校验通过
      let result;
      try {
        // 明确判断是否有id值，来决定执行更新还是新增操作
        console.log('Comment:', comment.value)
        if(comment.value.id){ 
          console.log('执行更新操作:', comment.value)
          result = await updateCommentApi(comment.value);
        } else { 
          console.log('执行新增操作:', comment.value)
          result = await addCommentApi(comment.value);
        }
        
        if(result.code){
          ElMessage.success(comment.value.id ? '更新评论成功' : '新增评论成功')
          dialogVisible.value = false
          handleSearch() // 重新查询列表数据
        } else { 
          ElMessage.error(result.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存出错:', error)
        ElMessage.error('保存过程中发生错误')
      }
    }
  })
}

// 存储选中的 ID
const selectedIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  const ids = selection.map(item => item.id);
  selectedIds.value = ids;
}

//批量删除评论
const deleteByIds = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的评论')
    return
  }
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除选中的评论吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除评论
    const result = await deleteCommentApi(selectedIds.value);
    if(result.code){
      ElMessage.success('删除评论成功')
      handleSearch()
    }else{
      ElMessage.error(result.msg || '删除失败')
    }
  })
}
</script>
<template> 
<h1>评论管理</h1> <br>
  <el-form :inline="true" :model="searchComment">
    <el-form-item label="评论内容">
      <el-input v-model="searchComment.content" placeholder="请输入评论内容"></el-input>
    </el-form-item>
    
    <el-form-item label="用户ID">
      <el-input v-model="searchComment.userId" placeholder="请输入用户ID" type="number"></el-input>
    </el-form-item>
    
    <el-form-item label="文章ID">
      <el-input v-model="searchComment.strategyId" placeholder="请输入文章ID" type="number"></el-input>
    </el-form-item>
    
    <el-form-item label="父评论ID">
      <el-input v-model="searchComment.parentId" placeholder="请输入父评论ID" type="number"></el-input>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addComment"> + 新增评论</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="commentList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50" align="center"></el-table-column>
    <el-table-column prop="id" label="评论ID" width="80" align="center"></el-table-column>
    <el-table-column prop="content" label="评论内容" align="center">
      <template #default="scope">
        {{ scope.row.content || '-' }}
      </template>
    </el-table-column>
    <el-table-column prop="userId" label="用户ID" width="100" align="center"></el-table-column>
    <el-table-column prop="userName" label="用户名" width="120" align="center">
      <template #default="scope">
        {{ scope.row.userName || '未知用户' }}
      </template>
    </el-table-column>
    <el-table-column prop="strategyId" label="文章ID" width="100" align="center"></el-table-column>
    <el-table-column prop="parentId" label="父评论ID" width="100" align="center">
      <template #default="scope">
        {{ scope.row.parentId || '-' }}
      </template>
    </el-table-column>
    <el-table-column prop="likeCount" label="点赞数" width="100" align="center"></el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
    <el-table-column label="操作" fixed="right" align="center" width="150">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改评论的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="commentFormRef" :model="comment" :rules="rules" label-width="80px">
        <el-form-item label="评论内容" prop="content">
          <el-input 
            v-model="comment.content" 
            placeholder="请输入评论内容"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="用户ID" prop="userId">
          <el-input 
            v-model.number="comment.userId" 
            placeholder="请输入用户ID"
            type="number"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="文章ID" prop="strategyId">
          <el-input 
            v-model.number="comment.strategyId" 
            placeholder="请输入文章ID"
            type="number"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="父评论ID">
          <el-input 
            v-model.number="comment.parentId" 
            placeholder="请输入父评论ID（可选）"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>

</template>
<style scoped> 
/* 可以根据需要添加自定义样式 */
</style>